package com.kikcn.demo.controllers;

import com.kikcn.demo.domain.Article;
import com.kikcn.demo.services.ArticleService;
import com.sun.istack.internal.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;

/**
 * User: Administrator
 * Date: 2015/3/12
 * Time: 21:56
 */
@Controller
@RequestMapping("/article")
public class ArticleController {
    private static final Integer PageSize = 10;
    private final static Logger logger = Logger.getLogger(ArticleController.class);
    @Autowired
    private ArticleService articleService;

    @RequestMapping(params = "method=create")
    public String create() {
        return "article/create";
    }

    @RequestMapping(params = "method=save")
    public String save(@Valid Article article, BindingResult result,ModelMap modelMap) {
        if (result.hasErrors()) {

            modelMap.addAttribute("errors",result.getAllErrors());
            return "article/create";
        }
        articleService.save(article);
        return "article/done";
    }

    @RequestMapping(params = "method=list")
    public String list(HttpServletRequest request, Integer pageNumber) {
        if (pageNumber == null) pageNumber = 0;
        Pageable pageRequest = new PageRequest(pageNumber, PageSize);

        Page<Article> data = articleService.list(pageRequest);
        request.setAttribute("page", data);
        return "article/list";
    }

    @RequestMapping(params = "method=delete")
    public String delete(Integer id) {
        articleService.delete(id);
        return "article/done";
    }

    @RequestMapping(params = "method=toUpdate")
    public String toUpdate(Integer id, ModelMap modelMap) {
        Article article = articleService.findOne(id);
        modelMap.addAttribute("article", article);
        return "article/update";
    }

    @RequestMapping(params = "method=update")
    public String toUpdate(@ModelAttribute("preloadArticle") Article article) {
        article.setLastEditTime(new Date());
        articleService.update(article);
        return "article/done";
    }

    @ModelAttribute("preloadArticle")
    public Article getUser(@RequestParam(value = "id", required = false) Integer id) {
        if (id != null) {
            return articleService.findOne(id);
        }
        return null;
    }

}
